//
//  NSData+CAIStorageBase64.m
//  CAIDBManager
//
//  Created by simon on 2021/11/5.
//

#import "NSData+CAIStorageBase64.h"

@implementation NSData (CAIStorageBase64)

//密钥归
+ (NSData *)base64EncodedData:(id)object error:(NSError * __autoreleasing *)error
{
    NSData *encodeData = nil;
    if (@available(iOS 11.0, *)) {
        NSError *error1;
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object requiringSecureCoding:YES error:&error1];
        if (error1)
        {
            if (error){
                *error = error1;
            }
            return nil;
        }
        else
        {
            encodeData = data;
        }
    }
    else
    {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object];
        encodeData = data;
    }
    encodeData = [encodeData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed|NSDataBase64EncodingEndLineWithCarriageReturn];
    return encodeData;
}

//密钥解
+ (id)base64DecodedData:(NSData *)base64Data
                  class:(Class)cls
                  error:(NSError * __autoreleasing *)error
{
    NSData *data = [[NSData alloc] initWithBase64EncodedData:base64Data options:0];
    if (@available(iOS 12.0, *)) {
        NSError *error1;
        id obj = [NSKeyedUnarchiver unarchivedObjectOfClass:cls fromData:data error:&error1];
        if (error1)
        {
            if (error) {
                *error = error1;
            }
            return nil;
        }
        return obj;
    }
    else
    {
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    return nil;
}




+ (NSString *)caiDBDecode:(NSString *)base64String
{
    NSData*data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}

+ (NSString *)caiDBEncode:(NSString *)string
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    return baseString;
}
@end
